
package com.mofang.ticketing.common.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mofang.ticketing.common.web.core.feign.FeignClientErrorDecoder;
import com.mofang.ticketing.common.web.core.feign.UnwrapDecoder;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;


/**
 * Feign相关配置类
 *
 * @author LGC
 */
@Configuration
public class FeignConfig {


    @Bean
    public RequestInterceptor requestInterceptor() {
        return (template) -> {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        template.header(name, values);
                    }
                }
            }
        };
    }

    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }

    @Bean
    public Request.Options options() {
        return new Request.Options(10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS, true);
    }

    @Bean
    public UnwrapDecoder unwrapDecoder(ObjectMapper objectMapper) {
        return new UnwrapDecoder(objectMapper);
    }

    @Bean
    public FeignClientErrorDecoder feignClientErrorDecoder(ObjectMapper objectMapper) {
        return new FeignClientErrorDecoder(objectMapper);
    }
}

